//
//  UserInfoTC.swift
//  甜言蜜语
//
//  Created by yingli on 16/7/21.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class UserInfoTC: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, RGFadeDelegate, UIAlertViewDelegate, ActionSheetCustomPickerDelegate{
    var model: userPersonInfo?{
        didSet{
            self.setupView()
        }
    }
    var actionSheet: UIActionSheet? = nil
    var imagePicker: UIImagePickerController? = nil
    
    var collectionStyleArr: [NSData]!//风采照片的流文件
    var msg: regiestInfo?
    var IMG: UIImage!
    var modityDic: NSDictionary?
    var rgFadeView: RGFadeView?
    var index: Int?
    
    var json: String?
    var type: String?
    var number: String?
    var comeFrom: String!
    
    @IBOutlet weak var imageHead: UIImageView!
    @IBOutlet weak var nickNameLbl: UILabel!
    @IBOutlet weak var signLbl: UILabel!
    @IBOutlet weak var sex: UILabel!
    @IBOutlet weak var birthday: UILabel!
    @IBOutlet weak var company: UILabel!
    @IBOutlet weak var work: UILabel!
    @IBOutlet weak var area: UILabel!
    
    
    @IBOutlet weak var phoneSwitch: UISwitch!
    @IBOutlet weak var wechatSwitch: UISwitch!
    @IBOutlet weak var tencentSwitch: UISwitch!
    @IBOutlet weak var sinaSwitch: UISwitch!
    
    @IBOutlet weak var phoneLbl: UILabel!
    @IBOutlet weak var wechatLbl: UILabel!
    @IBOutlet weak var tencentLbl: UILabel!
    @IBOutlet weak var sinaLbl: UILabel!
    
    var index1: NSInteger = 0 // 省下标
    var index2: NSInteger = 0 // 市下标
    var index3: NSInteger = 0 // 区下标
    
    var provinceArr: NSArray! //省
    var countryArr: NSArray! // 市
    var districtArr: NSArray! // 区
    var addressArr: NSArray! // 解析出来的最外层的数组
    
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.imageHead!.layer.masksToBounds = true
        self.imageHead!.layer.cornerRadius = 40
        self.getUserInfo()
        self.tableView.delegate = self
        self.actionSheet?.delegate = self
        self.title = "用户个人信息"
        self.phoneSwitch.hidden = true
        if (actionSheet == nil) {
            self.actionSheet = UIActionSheet(title: "选择照片",delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "拍照", "从手机相册选择")
        }
        self.calculateFirstData()

    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = NAVIGATIONBAR_RED_COLOR
        
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
   
    func calculateFirstData(){
        
        loadFirstData()
        let cityNameArr = NSMutableArray()
        
        print(addressArr.count)
        for cityName in (addressArr[index1].allValues.first) as! NSArray {
            
            let name1 = (cityName as! NSDictionary).allKeys.first
            cityNameArr.addObject(name1!)
        }
        // 组装对应省下面的市
        countryArr = cityNameArr
        
        districtArr = addressArr[index1].allObjects[0][index2].allValues[0] as! NSArray
        
    }
    func loadFirstData(){
        
        let path = NSBundle.mainBundle().pathForResource("address", ofType: "json")
        print(path)
        
        let data = NSData.init(contentsOfFile: path!)
        
        guard let myArr = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) else {
            
            return
        }
        
        addressArr = myArr as! NSArray
        
        let firstName = NSMutableArray()
        for dict in addressArr {
            
            let name = (dict as! NSDictionary).allKeys.first
            firstName.addObject(name!)
        }
        provinceArr = firstName
        
        
    }
    //MARK: UIPickerViewDataSource Implementation
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int{
        switch (component)
        {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
            
        default:break;
        }
        return 0;
    }
    
    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String?{
        
        switch (component)
        {
        case 0: return self.provinceArr[row] as? String
        case 1: return self.countryArr[row] as? String
            
        default:break;
        }
        return nil;
    }
    func pickerView(pickerView: UIPickerView,
                    viewForRow row: Int,
                               forComponent component: Int,
                                            reusing view: UIView?) -> UIView{
        
        
        let label: UILabel! = UILabel()
        label!.font = UIFont.systemFontOfSize(14)
        
        var title = ""
        switch component {
        case 0:
            title = self.provinceArr[row] as! String
        case 1:
            title = self.countryArr[row] as! String
            
        default:
            break
        }
        
        label!.textAlignment = NSTextAlignment.Center
        label!.text = title
        return label!
        
    }
    func pickerView(pickerView: UIPickerView,
                    didSelectRow row: Int,
                                 inComponent component: Int){
        switch component {
        case 0:
            self.index1 = row
            self.index2 = 0
            
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            self.calculateFirstData()
            pickerView.reloadComponent(1)
            
            pickerView.selectRow(0, inComponent: 1, animated: true)
            
            
        case 1:
            self.index2 = row
            
        default:
            break
        }
        
    }
    //MARK:点击完成的按钮时执行
    func actionSheetPickerDidSucceed(actionSheetPicker: AbstractActionSheetPicker!, origin: AnyObject!) {
        var detailAddress = String()
        if self.index1 < self.provinceArr.count {
            let firstAddress = self.provinceArr[self.index1]
            detailAddress += firstAddress as! String
        }
        if self.index2 < self.countryArr.count {
            let secondAddress = self.countryArr[self.index2]
            detailAddress += secondAddress as! String
        }
        
        // 此界面显示
        print(detailAddress)
        self.modityDic = ["unitarea": detailAddress]
        self.modifyUserInfo()
        
    }

   //MARK:tableViewDelegate
    
   override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        index = indexPath.row
        if indexPath.row == 0{
            self.actionSheet!.showInView(self.view!)
        }
        if indexPath.row == 1{
            
//            if (rgFadeView == nil) {
//                rgFadeView = RGFadeView.init(frame: kScreen_frame)
//                rgFadeView?.docid = "1"
//                rgFadeView?.delegate = self
//                self.view.addSubview(rgFadeView!)
//            }
//           
//            rgFadeView?.msgTextView.becomeFirstResponder()
        }
        if indexPath.row == 2{
            if (rgFadeView == nil) {
                rgFadeView = RGFadeView.init(frame: kScreen_frame)
                rgFadeView?.docid = "1"
                rgFadeView?.delegate = self
                self.view.addSubview(rgFadeView!)
            }
            
            rgFadeView?.msgTextView.becomeFirstResponder()
        }

        if indexPath.row == 3{
//            ActionSheetMultipleStringPicker.showPickerWithTitle("请选择性别", rows:[["男", "女"]],initialSelection: [1,1], doneBlock: {
//                picker, values, indexes in
//                let obj = (indexes as! NSArray)[0] as! String
//                self.modityDic = ["sex": obj]
//                self.modifyUserInfo()
//                return
//                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
            
        }
        if indexPath.row == 4{
//            ActionSheetDatePicker.showPickerWithTitle("出生年月", datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(), doneBlock: {(picker: ActionSheetDatePicker!, selectedDate: AnyObject!, origin: AnyObject!) -> Void in
//                
//                let obj = selectedDate as! NSDate
//                self.modityDic = ["birthday": publicMethod.dataFromString(obj)]
//                self.modifyUserInfo()
//                
//                }, cancelBlock: {(picker: ActionSheetDatePicker!) -> Void in
//                    print("cancel")
//                }, origin: self.view)
            
        }
        if indexPath.row == 5{
            if (rgFadeView == nil) {
                rgFadeView = RGFadeView.init(frame: kScreen_frame)
                rgFadeView?.docid = "1"
                rgFadeView?.delegate = self
                self.view.addSubview(rgFadeView!)
            }
            
            rgFadeView?.msgTextView.becomeFirstResponder()
        }
        if indexPath.row == 6{
            ActionSheetMultipleStringPicker.showPickerWithTitle("请选择职务", rows:[["美容院院长(职业经理人)", "美容师", "美容顾问(业务员)", "业务经理(职业经理人)", "美容顾问(业务员)", "讲师"]],initialSelection: [1,1], doneBlock: {
                picker, values, indexes in
                let obj = (indexes as! NSArray)[0] as! String
                self.modityDic = ["position": obj]
                self.modifyUserInfo()
                return
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
        }
        if indexPath.row == 7{
            
            ActionSheetCustomPicker.showPickerWithTitle("位置区域", delegate: self, showCancelButton: true, origin: self.view, initialSelections: [index1, index2])
           
        }
    }
    //MARK:target
    @IBAction func signOut(sender: UIButton){
        

        let alertView = UIAlertView(title: "退出", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
        
        alertView.show()

    }
    //MARK:alertDelegate
    func alertView(alertView: UIAlertView,clickedButtonAtIndex buttonIndex: Int){
        if (buttonIndex == 1){
            print("退出")
            DataTool.loginOut({ (newModel) in
                guard newModel != nil else {
                    return
                }
                self.msg = newModel
                SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
               
                NSUserDefaults.standardUserDefaults().setBool(false, forKey: "k_UD_isLogin")
                
                NSUserDefaults.standardUserDefaults().synchronize()
                
            self.navigationController?.popToRootViewControllerAnimated(true)
                
            })

           
        }
        
    }
    //MARK:更新显示信息
    func setupView(){
        self.imageHead.sd_setImageWithURL(NSURL(string: (self.model?.timg)!), placeholderImage: UIImage(named: "placeholder"))
        self.nickNameLbl.text = self.model?.name
        self.signLbl.text = self.model?.signature
        self.sex.text = self.model?.sex
        self.birthday.text = self.model?.birthday
        self.company.text = self.model?.unitname
        self.work.text = self.model?.membertypecn
        self.area.text = self.model?.unitarea
        self.phoneLbl.text = self.model?.phone
        self.wechatLbl.text = self.model?.weixinname
        self.tencentLbl.text = self.model?.qqname
        self.sinaLbl.text = self.model?.sinaname
        
        if self.model?.phone.characters.count > 0{
            self.phoneSwitch.on = true
        }else{
            self.phoneSwitch.on = false
        }
        
        if self.model?.weixinname.characters.count > 0{
            self.wechatSwitch.on = true
        }else{
            self.wechatSwitch.on = false
        }
        
        if self.model?.qqname.characters.count > 0{
            self.tencentSwitch.on = true
        }else{
            self.tencentSwitch.on = false
        }
        
        if self.model?.sinaname.characters.count > 0{
            self.sinaSwitch.on = true
        }else{
            self.sinaSwitch.on = false
        }

    }
    
    //MARK:actionSheetDelegate
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            //拍照
            var sourceType = UIImagePickerControllerSourceType.Camera
            if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
                
                sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            }
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true//设置可编辑
            picker.sourceType = sourceType
            self.presentViewController(picker, animated: true, completion: nil)//进入照相界面

        }else if buttonIndex == 2{
            //相册
            let pickerImage = UIImagePickerController()
            if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
                pickerImage.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                pickerImage.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(pickerImage.sourceType)!
            }
            
            pickerImage.delegate = self
            
            pickerImage.allowsEditing = true
            
            self.presentViewController(pickerImage, animated: true, completion: nil)
        }
    
    }
    //MARK:UIImagePickerControllerDelegate
    func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]){
        
        var img: UIImage!
        
        img = info[UIImagePickerControllerEditedImage] as! UIImage
        self.IMG = img
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        self.upUserHeadimg()
        
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController){
    
        print("cancel--------->>")
    
        picker.dismissViewControllerAnimated(true, completion: nil)

    }
    //MARK:RGFadeDelegate
    func sendBtnDown(text: String) {
        if index == 1{
            self.modityDic = ["name": text]
        }
        if index == 2{
             self.modityDic = ["signature": text]
        }
        if index == 3{
            self.modityDic = ["signature": text]
        }
        if index == 5{
            self.modityDic = ["unitname": text]
        }
        if index == 6{
            self.modityDic = ["position": text]
        }
        self.modifyUserInfo()
    }
    //MARK:绑定第三方
    @IBAction func stateChanged(switchState: UISwitch) {
        if switchState == phoneSwitch{//手机
            if switchState.on {
                
               
            } else {
                
            }
        }
        if switchState == wechatSwitch{//微信
            if switchState.on {
                ShareSDK.authorize(SSDKPlatformType.TypeWechat, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
                    
                    switch state{
                        
                    case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
                    self.json = "\(user)"
                    self.number = user.uid
                    self.bindingAccountNumber("weixin")//调第三方绑定
                    case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
                        self.wechatSwitch.on = false
                    case SSDKResponseState.Cancel:  print("操作取消")
                        self.wechatSwitch.on = false
                    default:
                        break
                    }
                })

            } else {
                self.type = "weixin"
                self.tiedThirdPartyAccount()
                
            }
        }
        if switchState == tencentSwitch{// 腾讯
            if switchState.on {
                ShareSDK.authorize(SSDKPlatformType.TypeQQ, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
                    
                    switch state{
                        
                    case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
                    self.json = "\(user)"
                    self.number = user.uid
                    self.bindingAccountNumber("qq")//调第三方绑定
                    case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
                        self.tencentSwitch.on = false
                    case SSDKResponseState.Cancel:  print("操作取消")
                         self.tencentSwitch.on = false
                    default:
                        break
                    }
                })
                
            } else {
                self.type = "qq"
                self.tiedThirdPartyAccount()
                
                
            }
        }
        if switchState == sinaSwitch{//新浪
            if switchState.on {
                ShareSDK.authorize(SSDKPlatformType.TypeSinaWeibo, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
                    
                    switch state{
                        
                    case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
                    self.json = "\(user)"
                    self.number = user.uid
                    self.bindingAccountNumber("sina")//调第三方绑定
                    case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
                        self.sinaSwitch.on = false
                    case SSDKResponseState.Cancel:  print("操作取消")
                        self.sinaSwitch.on = false
                    default:
                        break
                    }
                })

               
            } else {
                
                self.type = "sina"
                self.tiedThirdPartyAccount()
            }
        }
        
    }

    //MARK:networking
    //上传头像
    func upUserHeadimg(){

        DataTool.upload(self.IMG, completionHandler: { (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
            
            
            self.getUserInfo()
            
        })
    }
    //我的个人信息
    func getUserInfo(){
        DataTool.getUserInfomation({ (newModel) in
            guard newModel != nil else {
                return
            }
           self.model = newModel
        })

    }
    //修改个人信息
    func modifyUserInfo(){
        DataTool.modifyUserInfomation(self.modityDic!, completionHandler: { (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
          
            self.getUserInfo()

        })

    }
    //第三方绑定
    func bindingAccountNumber(type: String){
        let url = String(format: "%@user/binding/\(type)",BaseUrl)
        let paramDic = ["json": self.json!, "number": self.number!]
        
        DataTool.bingdingsThirdNumber(url, param: paramDic, completionHandler:({(newModel) in
            guard newModel != nil else {
            return
            }
            SVProgressHUD.showSuccessWithStatus(newModel?.msg)
            self.getUserInfo()
            
        }))
    }
    //解绑第三方账号
    func tiedThirdPartyAccount(){
        let url = String(format: "%@user/binding/dodel",BaseUrl)
        let paramDic = ["type": self.type!]
        
        DataTool.releaseThirdNumber(url, param: paramDic, completionHandler: ({(newModel) in
            guard newModel != nil else {
                return
            }
            SVProgressHUD.showSuccessWithStatus(newModel?.msg)
            self.getUserInfo()
            
        }))

    }
}

